﻿using CatUtils.Utils.Currency;
using CatUtils.Utils.Currency.IoUtils;
using CatUtils.Utils.Currency.TextUtils;
using CatUtils.Utils.Helper;
using CatUtils.Utils.SpecialUtils.Html;
using CatUtilsDll.Utils.Currency.WebUtils;
using Newtonsoft.Json;
using RabbitDownload.WebSite.Pixiv.Login;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace RabbitDownload.WebSite.Pixiv.PixivTag
{
    partial class PixivTagJsonNew
    {
        public static int JumpCountSetting = 5;//如果数据不正常多少次后跳出

        public static void ListFileBatch(string FilePath)
        {
            List<string> TagList = FileHelper.ReadAllLine(FilePath);
            int Complted = 0;
            foreach (var item in TagList)
            {
                string Jptag = HtmlHelper.GetFirstText(item, "//jptag");
                string CNtag = HtmlHelper.GetFirstText(item, "//cntag");
                if (Jptag != "" && CNtag != "")
                {
                    //   Scanner(Jptag, 1, 10000, "popular_male_d", "r18", 1000, true, CNtag + "-");
                    Scanner(Jptag, 1, 10000, "popular_male_d", "safe", 1000, true, CNtag + "-");
                }
                new PrintLog().PercentLog(TagList.Count, Complted++);
            }
        }

        /// <summary>
        /// 启动标签扫描
        /// </summary>
        /// <param name="Tag"></param>
        /// <param name="StartPage"></param>
        /// <param name="EndPage"></param>
        /// <param name="order">排序方式，全部popular_d 男性喜欢 popular_male_d 女性喜欢  popular_female_d</param>
        /// <param name="Mode">查看模式 全部 all 安全 safe 和谐r18</param>
        /// <param name="Score">分数 检查列表最后一张图是否是可看的</param>
        /// <param name="JumpComic"></param>
        /// <param name="FlieNameTip">需要额外在文件名追加的内容</param>
        /// <returns></returns>
        public static string Scanner(string Tag, int StartPage, int EndPage, string order, string Mode, int Score, bool JumpComic, string FlieNameTip = "")
        {
            string ListAPI = "https://www.pixiv.net/ajax/search/artworks/{0}?&order={1}&mode={2}&p={3}&s_mode=s_tag&type=all&lang=zh";
            List<string> ImgList = new List<string>();
            List<string> GifList = new List<string>();
            int JumpFlag = 0;

            #region 扫描文件的主循环

            for (; StartPage <= EndPage; StartPage++)
            {
                WebHeaderCollection webHeader = LoginHelper.InitHeader();
                string TempAPI = string.Format(ListAPI, WebHelper.UrlEncode(Tag), order, Mode, StartPage);

                Console.WriteLine(TempAPI);
                string Shtml = WebHelper.HttpGet(TempAPI, webHeader);
                string LastId = "";//分数不足的时候跳出判断

                try
                {
                    Root root = JsonConvert.DeserializeObject<Root>(Shtml);

                    SaveJsonData(Tag, StartPage, order, Mode, Shtml);
                    Console.WriteLine(root.body.illustManga.data.Count);
                    if (root.body.illustManga.data != null && root.body.illustManga.data.Count > 0)
                        foreach (var item in root.body.illustManga.data)
                        {
                            if (item.url == null)
                            {
                                Console.WriteLine(JsonConvert.SerializeObject(item));
                                Console.WriteLine("获取到的对象为空，有可能是作者删除了作品，这个情况目前只能判空。");
                                continue;
                            }
                            if (JumpComic && item.pageCount > 1)
                            {
                                PrintLog.E("跳过漫画");
                                continue;
                            }
                            string TempImg = JudegImage(item.url);
                            if (TempImg.IndexOf("_p0") > 0)
                                ImgList.Add(TempImg);
                            else
                                GifList.Add(TempImg);
                            Console.WriteLine(item.userName);
                            Console.WriteLine(TempImg);
                            LastId = item.illustId;
                        }
                    else
                    {
                        JumpFlag++;
                        PrintLog.E($"图集列表数据为空。{JumpCountSetting - JumpFlag}次后跳出。");

                        if (JumpFlag > JumpCountSetting)
                        {
                            PrintLog.E("图集列表数据为空。"); break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    PrintLog.E(ex);
                }

                if (LastId != "")
                {
                    int LastScore = GetScore(LastId, webHeader);
                    PrintLog.D($"预设分数{Score}当前分数{LastScore}");
                    if (Score > LastScore)
                    {
                        PrintLog.E("分数不足 结束扫描！");
                        break;
                    }
                }
            }

            #endregion 扫描文件的主循环

            WebCurrency.SaveHelper.AutoSave(ImgList, FlieNameTip + Tag, $"P站标签\\{TextHelper.ReplaceBadChar(Tag)}\\{order}-{Mode}\\");
            if (GifList.Count >= 0)
            {
                WebCurrency.SaveHelper.AutoSave(GifList, $"{FlieNameTip}-{Tag }-gif", $"P站标签\\{TextHelper.ReplaceBadChar(Tag)}\\{order}-{Mode}\\gif\\");
            }

            return "";
        }

        private static string JudegImage(string url)
        {
            url = url.Replace("/c/250x250_80_a2/custom-thumb", "/img-original").Replace("_custom1200", "");

            return url.Replace("/c/250x250_80_a2/img-master", "/img-original").Replace("_square1200", "");
        }

        private static void SaveJsonData(string tag, int startPage, string order, string mode, string shtml)
        {
            string FloderPath = StaticValue.TempPath + $"pixivjson\\{TextHelper.ReplaceBadChar(tag)}\\{order}-{mode}\\";
            FloderHelper.FloderExits(FloderPath, true);

            FileHelper.WriteText($"{FloderPath}{startPage}.json", shtml);
        }

        private static int GetScore(string LastId, WebHeaderCollection webHeader)
        {
            string API = "https://www.pixiv.net/bookmark_detail.php?illust_id=" + LastId;

            string Shtml = WebHelper.HttpGet(API, webHeader);

            return TextHelper.StringToInt(HtmlHelper.GetFirstText(Shtml, "//a[@class='bookmark-count _ui-tooltip']").Trim());
        }
    }
}